<template>
    <view class="xy-datetime">
        <view class="calendar">
            <view class="month">
                <view class="pre" @click="changeMonth('pre')">
                    <text>上个月</text>
                </view>
                <view>{{y+'年'+formatDay(m)+'月'}}</view>
                <view class="next" @click="changeMonth('next')">
                    <text>下个月</text>
                </view>
            </view>
            <view class="week">
                <view class="week-day" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
            </view>
            <view class="days">
                <view class="item" v-for="(item, index) in dates" :key="index">
                    <view class="day" @click="toggleDay(item)" :class="{
                        selectedDay: isDaySelected(item),
                        activeDay: isActiveDay(item),
                        noWorkDay: noWorkDay(item.year, item.month, item.date),
                        pastDay: isPastDay(item.year, item.month, item.date) // 🌟 新增：过去日期样式
                    }">
                        {{ isToday(item.year, item.month, item.date) ? '今' : Number(item.date) }}
                    </view>
                </view>
            </view>
        </view>
        <view class="timestr">
            <view class="title">选择时段：
                <text class="day" v-for="(dayInfo, index) in selectedBookings" :key="dayInfo.date"
                    @click="setActiveDayForTimes(dayInfo.date)"
                    :class="{ 'active-day-in-title': dayInfo.date === activeDateForTimeSelection }">
                    {{dayInfo.date}}{{index < selectedBookings.length-1 ? '、' : ''}}
                </text>
                <text v-if="!selectedBookings.length && !activeDateForTimeSelection"
                    class="placeholder-text">请在日历中选择日期</text>
            </view>

            <view class="list">
                <view class="item" v-for="(item, index) in availableTimeSlotsForActiveDate" :key="index"
                    @click="toggleTime(item)" :class="{
						selectedTime: isTimeSelected(item),
						'reservable': item.IsReserve == 1,
						'unreservable': item.IsReserve != 1
					}">
                    <view class="top">{{item.IsReserve == 1 ? '可选' : '不可选'}}</view>
                    <view>{{item.Name}}</view>
                </view>
                <view
                    v-if="activeDateForTimeSelection && (!availableTimeSlotsForActiveDate || availableTimeSlotsForActiveDate.length === 0)"
                    class="no-slots-message">
                    <text>当前日期没有可选择的时段</text>
                </view>
                <view v-if="!activeDateForTimeSelection && selectedBookings.length > 0" class="no-slots-message">
                    <text>请在上方已选日期中选择一个以查看时段</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    name: 'ren-calendar',
    props: {
        timeList: {
            type: Array,
            default: () => {
                return [];
            }
        },
        initParams: {
            type: Object,
            default: () => ({})
        }
    },
    data () {
        return {
            y: new Date().getFullYear(),
            m: new Date().getMonth() + 1,
            dates: [],
            weektext: ['日', '一', '二', '三', '四', '五', '六'],
            weekstart: 0,
            selectedBookings: [],
            activeDateForTimeSelection: '',
            availableTimeSlotsForActiveDate: []
        };
    },
    created () {
        this.dates = this.monthDay(this.y, this.m);
    },
    mounted () {
        const today = new Date();
        const todayStr =
            `${today.getFullYear()}-${this.formatDay(today.getMonth() + 1)}-${this.formatDay(today.getDate())}`;

        // 默认选中今天并将其设为激活日期，如果需要的话。
        // 根据业务需求，如果默认不能选中当天，可以去掉这部分。
        // 这里保留，因为通常今天是可以选择的。
		if(this.initParams.reserveDate){
			this.selectedBookings.push({ date: this.initParams.reserveDate, selectedTimes: [] });
			this.activeDateForTimeSelection = this.initParams.reserveDate;
		}else{
			if (!this.isPastDay(today.getFullYear(), today.getMonth() + 1, today.getDate())) {
			     this.selectedBookings.push({ date: todayStr, selectedTimes: [] });
			     this.activeDateForTimeSelection = todayStr;
			}
		}

        if (this.initParams && this.initParams.RoomId) {
            // 只有当今天不是过去日期时才获取时段，或者确保activeDateForTimeSelection有值才获取
            if (this.activeDateForTimeSelection) {
                 this.getTimeData(this.activeDateForTimeSelection);
            }
        }
    },
    computed: {
        weekDay () {
            return this.weektext.slice(this.weekstart).concat(this.weektext.slice(0, this.weekstart));
        },
    },
    watch: {
        initParams: {
            handler (newVal, oldVal) {
                if (newVal && newVal.RoomId !== (oldVal ? oldVal.RoomId : undefined)) {
                    if (this.activeDateForTimeSelection) {
                        this.getTimeData(this.activeDateForTimeSelection);
                    }
                }
            }
        },
        selectedBookings: {
            handler (newval) {
                this.$emit('onChooseDatetime', [...newval]);
                console.log('Component Emitting: onChooseDatetime', JSON.parse(JSON.stringify(newval)));
            },
            deep: true
        },
        activeDateForTimeSelection: {
            handler (newVal, oldVal) {
                if (newVal && newVal !== oldVal) {
                    this.getTimeData(newVal);
                } else if (!newVal && oldVal) {
                    this.availableTimeSlotsForActiveDate = [];
                }
            }
        }
    },
    methods: {
        formatDay (num) {
            let res = Number(num);
            return res < 10 ? '0' + res : res;
        },
        getToday () {
            let date = new Date();
            let y = date.getFullYear();
            let m = date.getMonth();
            let d = date.getDate();
            return y + '-' + this.formatDay(m + 1) + '-' + this.formatDay(d);
        },
        // 🌟 新增辅助方法：获取格式化的日期字符串 (YYYY-MM-DD)
        getFormattedDate (year, month, date) {
            return `${year}-${this.formatDay(month)}-${this.formatDay(date)}`;
        },
        // 🌟 新增：判断日期是否在今天之前
        isPastDay (year, month, date) {
            const todayStr = this.getToday(); // 获取今天的 YYYY-MM-DD 字符串
            const currentDayStr = this.getFormattedDate(year, month, date); // 获取传入日期的 YYYY-MM-DD 字符串

            return currentDayStr < todayStr; // 直接比较字符串可以判断日期先后
        },

        monthDay (y, month) {
            let dates = [];
            let m = Number(month);

            let firstDayOfMonth = new Date(y, m - 1, 1).getDay();
            let lastDateOfMonth = new Date(y, m, 0).getDate();
            let lastDayOfLastMonth = new Date(y, m - 1, 0).getDate();

            let weekstart = this.weekstart == 7 ? 0 : this.weekstart;

            let startDay = (() => {
                if (firstDayOfMonth == weekstart) {
                    return 0;
                } else if (firstDayOfMonth > weekstart) {
                    return firstDayOfMonth - weekstart;
                } else {
                    return 7 - weekstart + firstDayOfMonth;
                }
            })();

            let endDay = 7 - ((startDay + lastDateOfMonth) % 7);
            if (endDay === 7) endDay = 0;

            for (let i = 1; i <= startDay; i++) {
                let prevMonth = m - 1;
                let prevYear = y;
                if (prevMonth < 1) {
                    prevMonth = 12;
                    prevYear--;
                }
                dates.push({
                    date: this.formatDay(lastDayOfLastMonth - startDay + i),
                    day: new Date(prevYear, prevMonth - 1, lastDayOfLastMonth - startDay + i).getDay(),
                    month: this.formatDay(prevMonth),
                    year: prevYear
                });
            }

            for (let j = 1; j <= lastDateOfMonth; j++) {
                dates.push({
                    date: this.formatDay(j),
                    day: new Date(y, m - 1, j).getDay(),
                    month: this.formatDay(m),
                    year: y,
                });
            }

            for (let k = 1; k <= endDay; k++) {
                let nextMonth = m + 1;
                let nextYear = y;
                if (nextMonth > 12) {
                    nextMonth = 1;
                    nextYear++;
                }
                dates.push({
                    date: this.formatDay(k),
                    day: new Date(nextYear, nextMonth - 1, k).getDay(),
                    month: this.formatDay(nextMonth),
                    year: nextYear
                });
            }
            return dates;
        },
        noWorkDay (y, m, d) {
            let ymd = `${y}/${m}/${d}`;
            let formatDY = new Date(ymd.replace(/-/g, '/'));
            let week = formatDY.getDay();
            if (week == 0 || week == 6) {
                return true;
            } else {
                return false;
            }
        },
        isToday (y, m, d) {
            let checkD = y + '-' + m + '-' + d;
            let today = this.getToday();
            if (checkD == today) {
                return true;
            } else {
                return false;
            }
        },

        toggleDay (item) {
            // 🌟 核心改动：如果日期是过去日期，则直接返回，不执行任何操作
            if (this.isPastDay(item.year, item.month, item.date)) {
                // 可以添加一个提示消息（例如uni.showToast）告知用户
                // uni.showToast({
                //     title: '过去的日期不可选择',
                //     icon: 'none',
                //     duration: 1500
                // });
                return;
            }

            const dateStr = `${item.year}-${item.month}-${item.date}`;
            const existingBookingIndex = this.selectedBookings.findIndex(b => b.date === dateStr);

            if (existingBookingIndex === -1) {
                this.selectedBookings.push({ date: dateStr, selectedTimes: [] });
                this.activeDateForTimeSelection = dateStr;
            } else {
                this.selectedBookings.splice(existingBookingIndex, 1);

                if (this.activeDateForTimeSelection === dateStr) {
                    if (this.selectedBookings.length > 0) {
                        this.activeDateForTimeSelection = this.selectedBookings[0].date;
                    } else {
                        this.activeDateForTimeSelection = '';
                        this.availableTimeSlotsForActiveDate = [];
                    }
                }
            }
        },

        isDaySelected (item) {
            const dateStr = `${item.year}-${item.month}-${item.date}`;
            return this.selectedBookings.some(b => b.date === dateStr);
        },

        isActiveDay (item) {
            const dateStr = `${item.year}-${item.month}-${item.date}`;
            return this.activeDateForTimeSelection === dateStr;
        },

        setActiveDayForTimes (dateStr) {
            this.activeDateForTimeSelection = dateStr;
        },

        toggleTime (item) {
            if (item.IsReserve !== 1) {
                return;
            }

            if (!this.activeDateForTimeSelection) {
                console.warn("No active date selected for time slot selection.");
                return;
            }

            const activeBooking = this.selectedBookings.find(b => b.date === this.activeDateForTimeSelection);

            if (activeBooking) {
                const timeIndex = activeBooking.selectedTimes.findIndex(t => t.Name === item.Name);

                if (timeIndex === -1) {
                    activeBooking.selectedTimes.push(item);
                } else {
                    activeBooking.selectedTimes.splice(timeIndex, 1);
                }
            }
        },

        isTimeSelected (item) {
            if (!this.activeDateForTimeSelection) {
                return false;
            }
            const activeBooking = this.selectedBookings.find(b => b.date === this.activeDateForTimeSelection);
            return activeBooking ? activeBooking.selectedTimes.some(t => t.Name === item.Name) : false;
        },

        changeMonth (type) {
            if (type == 'pre') {
                if (this.m === 1) {
                    this.m = 12;
                    this.y--;
                } else {
                    this.m--;
                }
            } else {
                if (this.m === 12) {
                    this.m = 1;
                    this.y++;
                } else {
                    this.m++;
                }
            }
            this.dates = this.monthDay(this.y, this.m);
        },

        async getTimeData (dateStr) {
			console.log("AAAAAA",this.initParams,dateStr)
            if (!this.initParams || !this.initParams.RoomId) {
                console.warn("initParams.RoomId is missing. Cannot fetch time slots.");
                this.availableTimeSlotsForActiveDate = [];
                return;
            }
            try {
                const res = await this.$u.api.getTimeSoltData({ roomId: this.initParams.RoomId, reserveDate: dateStr });
                if (res.code == 200) {
                    this.availableTimeSlotsForActiveDate = res.data || [];
                } else {
                    console.error("Failed to fetch time slots for", dateStr, ":", res.msg);
                    this.availableTimeSlotsForActiveDate = [];
                }
            } catch (e) {
                console.error("Error fetching time slots for", dateStr, ":", e);
                this.availableTimeSlotsForActiveDate = [];
            }
        }
    }
};
</script>

<style lang="scss">
page {
    background-color: #f1f1f1;
}

.xy-datetime {
    color: #191919;
    font-size: 28rpx;
    text-align: center;

    .timestr {
        background-color: #fff;
        margin: 30rpx;
        border-radius: 20rpx;
        padding: 30rpx;

        .title {
            text-align: left;
            margin-bottom: 20rpx;
            min-height: 40rpx;

            .day {
                color: #898786;
                margin-right: 20rpx;
                display: inline-block;
                padding: 4rpx 8rpx;
                border-radius: 8rpx;
                cursor: pointer;
                border: 1rpx solid transparent;

                &.active-day-in-title {
                    color: #D28E29;
                    font-weight: bold;
                    background-color: rgba(210, 142, 41, 0.1);
                    border: 1rpx solid #D28E29;
                }
            }

            .placeholder-text {
                color: #898786;
                font-size: 26rpx;
            }
        }

        .list {
            font-weight: 26rpx;
            display: flex;
            flex-wrap: wrap;
            padding-top: 10rpx;

            .item {
                border: solid 4rpx #fff;
                // background-color: rgba(95, 71, 67, 0.1);
                width: calc((100% - 40rpx) / 3);
                margin-top: 20rpx;
                padding-bottom: 15rpx;
                border-radius: 10rpx;
                overflow: hidden;
                margin-right: 20rpx;
                box-sizing: border-box;

                &:nth-child(3n) {
                    margin-right: 0;
                }

                .top {
                    background-color: rgba(95, 71, 67, 0.15);
                    padding: 8rpx 0;
                    margin-bottom: 15rpx;
                }
            }

            .selectedTime {
                border: solid 4rpx #5F4743;
                background-color: rgba(95, 71, 67, 0.3);
                color: #fff;

                .top {
                    background-color: rgba(95, 71, 67, 0.4);
                }
            }
        }

        .no-slots-message {
            width: 100%;
            text-align: center;
            color: #898786;
            padding: 30rpx 0;
            font-size: 26rpx;
        }
    }

    .calendar {
        background-color: #fff;
        margin:20rpx 30rpx 0 30rpx;
        border-radius: 20rpx;

        .month {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 90rpx;
            font-weight: bold;

            .pre,
            .next {
                display: flex;
                font-weight: normal;
                color: #898786;
                font-size: 28rpx;
                line-height: 28rpx;
                padding: 0 30rpx;
            }
        }

        .week {
            display: flex;
            align-items: center;
            height: 80rpx;
            line-height: 80rpx;
            color: #898786;

            .week-day {
                flex: 1;
            }
        }

        .days {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            position: relative;
            padding-bottom: 20rpx;

            .item {
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 80rpx;
                width: calc(100% / 7);

                .day {
                    font-style: normal;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 80rpx;
                    height: 60rpx;
                    overflow: hidden;
                    border-radius: 15rpx;
                    cursor: pointer;
                    border: 2rpx solid transparent;

                    &.selectedDay {
                        background-color: #D28E29;
                        color: #fff;
                    }

                    &.activeDay {
                        border: 2rpx dashed #D28E29;
                        box-sizing: border-box;
                    }

                    // 🌟 新增：过去日期样式
                    &.pastDay {
                        color: #ccc; /* 浅灰色字体 */
                        cursor: not-allowed; /* 鼠标变为禁止手势 */
                        background-color: #f8f8f8; /* 略微不同的背景色 */
                        border-color: transparent; /* 保持透明边框 */
                    }
                }

                .noWorkDay {
                    // 如果过去日期同时是周六日，这个样式可能会被覆盖，
                    // 但由于 pastDay 已经禁用了点击，所以视觉提示更重要
                    // 可以调整优先级，或者让pastDay覆盖noWorkDay的颜色
                    color: #898786; // 维持原有非工作日颜色，但pastDay会有更高的优先级
                }
            }
        }
    }
	
	.reservable{
		background-color: rgba(95, 71, 67, 0.3);
	}
	
	.unreservable{
		background-color: rgba(95, 71, 67, 0.1);
	}
}
</style>